package com.global.emc.core.components.token.impl;

import java.security.SecureRandom;
import java.util.Random;

import com.global.emc.core.components.token.Token;

/**
 * 
 * @Description: [一句话描述该类的功能]
 * @Author: [Joly_Huang]
 * @CreateDate: [2014年1月30日 下午12:26:35]
 * @UpdateUser: [Joly_Huang]
 * @UpdateDate: [2014年1月30日 下午12:26:35]
 * @UpdateRemark: [说明本次修改内容]
 * @Version: [v1.0]
 * 
 */
public class RandomNumberToken implements Token {
	

	private static Random random = new SecureRandom();
	
	private int tokenLength;
	private boolean flag;
	private long accessDate = System.currentTimeMillis();
	private String uniqueId;
	private boolean unavailable = false;
	
	public RandomNumberToken(int tokenLength, boolean flag){
		this.tokenLength = tokenLength;
		this.flag = flag;
		this.uniqueId=generateUniqueId();
	}

	@Override
	public long getAccessDate() {
		return accessDate;
	}
	@Override
	public String getUniqueId() {
		return uniqueId;
	}
	@Override
	public boolean isUnavailable() {
		return unavailable;
	}
	@Override
	public void setUnavailable(boolean unavailable) {
		this.unavailable = unavailable;
	}

	private String generateUniqueId(){
		long randomNum = random.nextLong();
		long posRandomNum = randomNum < 0L ? -randomNum : randomNum;
		StringBuilder stringBuilder;
		for (stringBuilder = new StringBuilder(flag ? Long.toString(posRandomNum) : Long.toString(posRandomNum, 36)); stringBuilder.length() < tokenLength; stringBuilder.insert(0, '0'));
		if (stringBuilder.length() > tokenLength)
			return stringBuilder.substring(stringBuilder.length() - tokenLength);
		else
			return stringBuilder.toString();
	}

	@Override
	public String toString() {
		return "RandomNumberToken [tokenLength=" + tokenLength + ", flag="
				+ flag + ", accessDate=" + accessDate + ", uniqueId="
				+ uniqueId + "]";
	}

}
